/* --------------------------------------------------------------------	*
 * slave_mpi.c															*
 * 																		*
 * Slave program for adding array elements using MPI.					*
 * --------------------------------------------------------------------	*/
#include <stdio.h>
#include <stdlib.h>
#include <lam/mpi.h>		/* MPI functions and constants	*/
#include "tags.h"			/* message tags					*/
#include "common.h"			/* common constants				*/

#define MASTER	0			/* rank of the master			*/

int main(int argc, char** argv)
{
	int items[DATA_SIZE];
	int size, sum, i;
	MPI_Status status;

	/* initialize the MPI system			*/
	MPI_Init(&argc, &argv);

	/* check for proper number of processes	*/
	MPI_Comm_size(MPI_COMM_WORLD, &size);

	if(size != 5)
	{
		fprintf(stderr, "Error: Need exactly five processes.\n");
		MPI_Finalize();
		exit(EXIT_FAILURE);
	}

	/* receive data from the master			*/
	MPI_Recv(items, DATA_SIZE, MPI_INT, MASTER, MSG_DATA,
			 MPI_COMM_WORLD, &status);

	/* find the sum							*/
	sum = 0;
	for(i = 0; i < DATA_SIZE; i++)
		sum = sum + items[i];

	/* send the result to the master		*/
	MPI_Send(&sum, 1, MPI_INT, MASTER, MSG_RESULT, MPI_COMM_WORLD);

	/* clean up and exit MPI system			*/
	MPI_Finalize();

	exit(EXIT_SUCCESS);
} /* end mai() */

/* end slave_mpi.c */

	
